package com.zy.baselib.widget

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.AttrRes
import com.zy.baselib.R

/**
 * @author: shalei
 * @since: 2020-02-28 15:29
 * @Desc: 缺省view
 **/
class StateView(
    context: Context, attrs: AttributeSet?,
    @AttrRes defStyleAttr: Int
) : FrameLayout(context, attrs, defStyleAttr) {

    private var emptyId: Int
    private var errorId: Int
    private var contentView: ImageView

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context) : this(context, null)

    init {
        val oa = context.obtainStyledAttributes(attrs, R.styleable.StateView)
        emptyId = oa.getResourceId(R.styleable.StateView_sv_empty_icon, R.mipmap.icon_empty)
        errorId = oa.getResourceId(R.styleable.StateView_sv_error_icon, R.mipmap.icon_error)
        oa.recycle()
        contentView = ImageView(context)
    }

    public fun error(id: Int = errorId) {
        addContentView(id)
    }

    public fun empty(id: Int = emptyId) {
        addContentView(id)
    }

    private fun addContentView(id: Int) {
        if (contentView.parent == null) {
            val l = LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            l.gravity = Gravity.CENTER
            this.addView(contentView, l)
        }
        contentView.setImageResource(id)
    }

}